package org.iot.iotserver.netty.command;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.ChannelHandlerContext;
import org.iot.iotserver.netty.config.NettyConstant;
import org.iot.iotserver.netty.entity.ADevice;
import org.iot.iotserver.service.IIOTCommonService;

import java.util.Arrays;

/**
 * 查询设备状态命令解析执行器
 */
public class ReadDeviceInfoCommandExecutor implements IYCommandExecutor<String> {

    private static final Log log = LogFactory.get();

    private final IIOTCommonService iotCommonService;

    public ReadDeviceInfoCommandExecutor(IIOTCommonService iotCommonService) {
        this.iotCommonService = iotCommonService;
    }

    @Override
    public boolean isMatching(String commandMetaData) {
        if(StrUtil.isEmpty(commandMetaData)) {
            return false;
        }
        String[] arr = commandMetaData.split("\\s+");
        if(arr.length < 3 || !"device-info".equalsIgnoreCase(arr[0])) {
            return false;
        }
        return true;
    }

    /**
     * 设备端设备数据上送的监控信息保存至缓存
     * @param args 第一个代表客户身份 ID, 第二个参数代表设备名称
     */
    @Override
    public String execute(ChannelHandlerContext context, String... args) {
        log.info("ReadDeviceInfoCommandExecutor({})", Arrays.toString(args));

        if(!NettyConstant.LEGAL_MONITORS.contains(args[0])) {
            return "illegal client\r\n";
        }

        String deviceName = args[1];
        if(NettyConstant.DEVICE_CACHE.containsKey(deviceName)) {
            ADevice device = NettyConstant.DEVICE_CACHE.get(deviceName);
            String deviceJsonData = JSONUtil.toJsonStr(device);
            return deviceJsonData;
        }

        return "unknown device\r\n";
    }
}
